package com.cloud.mall.conf.feign;


import cn.hutool.json.JSONUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: 梁二东
 * @Date: 2024/12/7 22:08
 * @Description:
 **/

@Slf4j
public class CustomFeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //RequestContextHolder.setRequestAttributes(attributes, true);
        requestTemplate.header("isFeign", "true");
        if (Objects.nonNull(attributes)) {
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (Objects.nonNull(headerNames)) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    String values = request.getHeader(name);
                    requestTemplate.header(name, values);
                }
            }
            Map<String, Collection<String>> headers = requestTemplate.headers();
            log.info("headers参数：{}", JSONUtil.toJsonStr(headers));

//            Enumeration<String> requestParams = request.getParameterNames();
//            StringBuffer paramStr = new StringBuffer();
//            if (requestParams != null) {
//                while (requestParams.hasMoreElements()) {
//                    String name = requestParams.nextElement();
//                    String values = request.getParameter(name);
//                    paramStr.append(name).append("=").append(values).append("&");
//                }
//            }
//            log.info("url参数：{}", paramStr);


//            if (paramStr.length() != 0) {
//                paramStr.deleteCharAt(paramStr.length() - 1);
//                Request.Body requestbody = Request.Body.create(String.valueOf(paramStr), Charset.defaultCharset());
//                requestTemplate.body(requestbody);
//                log.info("feign interceptor paramStr:{}", paramStr);
//            }
        }
    }
}
